import request from 'superagent'
import * as types from '../constant/action-type'
import {message} from 'antd'
import {getHeaderFromLocalStorage} from '../constant/authenticaiton'

const getSubmission = (data) => ({
  type: types.GET_TW_LOGIC_QUIZ_SUBMISSION,
  data
})
const getSubmissionSummary = (data) => ({
  type: types.GET_TW_LOGIC_QUIZ_SUBMISSION_SUMMARY,
  data
})

const getQuizItem = (data) => ({
  type: types.GET_TW_LOGIC_QUIZ_ITEM,
  data
})

const submitAnswers = (data) => ({
  type: types.SUBMIT_LOGIC_QUIZ_ITEM_ANSWERS,
  data
})

export const loadQuizSubmission = ({assignmentId, quizId, quizItemOrderNum}) => {
  return async dispatch => {
    const response = await request
      .get('api/tw-logic-quiz-submission')
      .set('id', 1)
      .set('token', getHeaderFromLocalStorage('jwt'))
      .set('sessionId', getHeaderFromLocalStorage('sessionId'))
      .query({assignmentId, quizId})

    if (!response.ok) {
      return
    }

    const body = response.body
    // 附加答案
    const {twlogicQuizItemAnswer, twexampleLogicQuizItemAnswer} = body
    body.twlogicQuizItemAnswer = twexampleLogicQuizItemAnswer.concat(twlogicQuizItemAnswer)

    dispatch(getSubmission(body))

    const idx = parseInt(quizItemOrderNum, 10) - 1
    const answerItem = response.body.twlogicQuizItemAnswer[idx]
    const quizResponse = await request
      .get(`api/v3/logicQuizzesItem/${answerItem.quizItemId}`)
      .set('id', 1)
      .set('token', getHeaderFromLocalStorage('jwt'))
      .set('sessionId', getHeaderFromLocalStorage('sessionId'))
    // 合并题目和答案
    const data = Object.assign({}, quizResponse.body, answerItem)
    dispatch(getQuizItem(data))
  }
}

export const submitQuizItemAnswer = (answerData) => {
  return async dispatch => {
    const response = await request
      .post('api/tw-logic-quiz-submission/answer')
      .send(answerData)
      .set('id', 1)
      .set('token', getHeaderFromLocalStorage('jwt'))
      .set('sessionId', getHeaderFromLocalStorage('sessionId'))

    if (response.ok) {
      dispatch(submitAnswers(answerData.answers))
      message.success('提交成功')
    }
  }
}

export const loadQuizSubmissionSummary = ({assignmentId, quizId}) => {
  return async dispatch => {
    const response = await request
      .get('api/tw-logic-quiz-submission/summary')
      .set('id', 1)
      .set('token', getHeaderFromLocalStorage('jwt'))
      .set('sessionId', getHeaderFromLocalStorage('sessionId'))
      .query({assignmentId, quizId})

    if (!response.ok) {
      return
    }
    dispatch(getSubmissionSummary(response.body))
  }
}
